import {createOrder, querySingleItem} from "@src/api/catering";
import $math from "@src/common/math";
import router from "@src/router";
import payBehavior from "../order/payBehavior";
import {getWxaMsgTpl} from "@src/api/base";
import wxUtils from "@src/common/wxUtils";

Component({
  behaviors: [payBehavior],
  data: {
    packingArray: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], //付费开卡状态选择
    item: null,
    shopInfo: null,
    singleData: null,
    itemId: null,
    tmplIdsData  : null,
    shopId: null,
    printerTag: '',
    buyNumber: 1,
  },
  methods: {
    onLoad(options) {
      let {itemId, shopId, printerTag} = options;
      this.setData({itemId, shopId, printerTag})
    },
    onLogin() {
      this.fetchData();
    },
    fetchData() {
      let data = {
        itemId: this.data.itemId,
        shopId: this.data.shopId
      };
      querySingleItem(data).then(res => {
        if (res.code === 0) {
          let {item, shopInfo} = res.data;
          let singleData = res.data;
          this.setData({item, shopInfo, singleData, totalFee: singleData.payFee})
          this.isPageLoadingFinish = true;
        }
      })
      getWxaMsgTpl({ bizCode: "CANYIN_PLACE_ORDER" }).then(res => {
        if (res.code === 0) {
          let tmplIdsData = res.data;
          this.setData({tmplIdsData})
        }
      })
    },
    handlePickerChange(e) {
      console.info("handlePickerChange", e)
      let buyNumber = parseFloat(e.detail.value) + 1;
      let totalFee = $math.mul(this.data.singleData.payFee, buyNumber, 2);
      this.setData({buyNumber, totalFee})
    },
    handleToPay() {
      if (this.data.tmplIdsData) {
        wxUtils.requestSubscribeMessage(this.data.tmplIdsData).then(res => {
          this.startCreateOrder()
        }).catch(()=> {
          this.startCreateOrder()
        })
      } else {
        this.startCreateOrder()
      }
    },
    startCreateOrder() {
      wx.showLoading({title: "下单中...", mask: true});
      let data = {
        items: [{count: this.data.buyNumber, itemId: this.data.itemId}],
        shopId: this.data.shopId,
        tradeType: 1,
        orderType: 1,
        printerTag: this.data.printerTag,
      }
      createOrder(data).then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          let orderNo = res.data.orderNo
          let params = {
            orderNo: orderNo,
            payFee: $math.mul(this.data.totalFee, 100, 0),
            hasDiscount: false,
            payChannels: ['wx']
          }
          this.toCateringPay(params).then((res) => {
            console.info("success", res)
            router.push({
              name: "catering/gklPaySuccess",
              params: {orderNo: orderNo}
            })
          }).catch(res => {
            console.error("res")
          });
        }
      })
    },

  }
})
